<template>
  <q-dialog v-model="visible">
    <q-card
      style="max-width: 90vw; max-height: calc(100vh - 2rem)"
      class="overflow-hidden"
    >
      <q-card-section class="text-h6">修改地图</q-card-section>
      <q-separator />
      <div style="max-height: calc(100vh - 9rem); overflow-y: auto">
        <q-card-section class="q-gutter-y-sm">
          <q-input outlined v-model="map.id" label="ID" readonly />
          <q-input outlined v-model="map.name" label="地图名称" />
          <q-select
            outlined
            v-model="map.type"
            :options="navigationTypes"
            label="地图类型"
            emit-value
            map-options
            behavior="menu"
          />
          <q-input
            type="number"
            outlined
            v-model="map.level"
            label="电梯层数"
          />
          <template v-if="['slam', 'ros'].includes(map.type)">
            <div class="row q-gutter-x-sm" style="max-width: 15rem">
              <q-input
                class="col"
                type="number"
                outlined
                v-model="map.height"
                label="高度"
              />
              <q-input
                class="col"
                type="number"
                outlined
                v-model="map.width"
                label="宽度"
              />
            </div>
            <q-input
              type="number"
              outlined
              v-model="map.resolution"
              label="分辨率"
            />
          </template>
          <q-select
            :use-input="!map.group"
            outlined
            behavior="menu"
            v-model="map.group"
            :options="groups"
            @new-value="newGroup"
            label="选择或新增地图组"
            clearable
          />
          <template v-if="['slam', 'ros'].includes(map.type)">
            <q-separator />
            <q-field label="SLAM导航地图" outlined stack-label>
              <template v-slot:control>
                <div class="row q-gutter-x-sm q-mt-xs">
                  <q-btn
                    icon="archive"
                    color="secondary"
                    class="col"
                    @click="download"
                    label="下载"
                  />
                  <q-btn
                    icon="unarchive"
                    color="primary"
                    class="col"
                    @click="mapUploader.show(map.id)"
                    label="上传"
                  />
                </div>
              </template>
            </q-field>
            <q-separator />
            <q-field label="可视化地图" outlined stack-label>
              <template v-slot:control>
                <div class="row q-gutter-x-sm q-mt-xs">
                  <q-btn
                    icon="archive"
                    color="secondary"
                    class="col"
                    @click="downloadRemote"
                    label="下载"
                  />
                  <q-btn
                    icon="unarchive"
                    color="primary"
                    class="col"
                    @click="remoteMapUploader.show(map.id)"
                    label="上传"
                  />
                </div>
              </template>
            </q-field>
          </template>
          <div>
            <q-btn
              icon="cleaning_services"
              label="点位连线清理"
              color="accent"
              class="full-width"
              @click="lineClean"
            />
          </div>
          <div>
            <q-btn
              icon="file_copy"
              label="复制地图"
              color="primary"
              class="full-width"
              @click="mapCopy"
            />
          </div>
        </q-card-section>
      </div>
      <transition-fade>
        <q-card-section class="q-pa-none row" v-if="modified">
          <q-btn
            stretch
            color="primary"
            class="col"
            label="修改地图"
            @click="update"
          />
          <q-btn
            stretch
            color="secondary"
            class="col"
            label="还原地图"
            @click="reset"
          />
        </q-card-section>
        <q-card-section class="q-pa-none row" v-else>
          <q-btn
            stretch
            color="negative"
            class="col"
            label="删除地图"
            @click="remove"
          />
        </q-card-section>
      </transition-fade>
    </q-card>
    <map-img-uploader ref="mapUploader" />
    <map-img-uploader ref="remoteMapUploader" remote />
  </q-dialog>
</template>

<script>
import { ref, computed, inject } from "vue";
import { api } from "boot/axios";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api";

import MapImgUploader from "components/rosMapRemote/map/MapImgUploader.vue";
import TransitionFade from "components/animations/Fade.vue";

export default {
  name: "ModifyMap",
  components: { TransitionFade, MapImgUploader },
  setup(props, context) {
    const $q = useQuasar();
    const visible = ref(false);
    const originMap = ref({});
    const map = ref({
      id: "",
      name: "",
      type: "",
      level: 0,
      group: "",
    });

    const groups = ref([]);
    function getGroup() {
      api.get(useAPIStore().mapUrl + "map/groups").then((rs) => {
        groups.value = rs.data;
      });
    }

    return {
      visible,
      map,
      originMap,
      groups,
      show(data) {
        getGroup();
        originMap.value = data;
        map.value = JSON.parse(JSON.stringify(data));
        visible.value = true;
      },
      modified: computed(
        () => JSON.stringify(originMap.value) !== JSON.stringify(map.value)
      ),
      update() {
        api.put(useAPIStore().mapUrl + "map/simple", map.value).then((rs) => {
          if (rs.data === "modified") {
            $q.notify({ message: "地图修改成功", type: "positive" });
            visible.value = false;
            context.emit("update");
          }
        });
      },
      reset() {
        map.value = JSON.parse(JSON.stringify(originMap.value));
      },
      remove() {
        $q.dialog({
          title: "操作前确认",
          message: "是否要删除当前地图？",
          cancel: true,
        }).onOk(() => {
          api
            .delete(useAPIStore().mapUrl + "map/" + map.value.id)
            .then((rs) => {
              if (rs.status === 200) {
                visible.value = false;
                $q.notify({ type: "positive", message: "地图删除成功" });
                context.emit("update");
              }
            });
        });
      },
      download() {
        api.get(useAPIStore().mapUrl + "map/id/" + map.value.id).then((rs) => {
          const imgUrl = "data:image/png;base64," + rs.data.mapBase64;
          const a = document.createElement("a");
          a.href = imgUrl;
          a.setAttribute("download", map.value.name);
          a.click();
        });
      },
      downloadRemote() {
        api.get(useAPIStore().mapUrl + "map/id/" + map.value.id).then((rs) => {
          const imgUrl = "data:image/png;base64," + rs.data.mapRemote64;
          const a = document.createElement("a");
          a.href = imgUrl;
          a.setAttribute("download", map.value.name);
          a.click();
        });
      },
      lineClean() {
        api
          .get(useAPIStore().mapUrl + "map/clear/line/" + map.value.id)
          .then((rs) => {
            if (rs.data === 0) {
              $q.notify({
                type: "positive",
                message: "当前地图已经没有无效的连线",
                position: "top",
              });
            } else {
              $q.notify({
                type: "info",
                message: "已清除" + rs.data + "条无效连线",
                position: "top",
              });
            }
            context.emit("updatePose");
          });
      },
      mapCopy() {
        $q.dialog({
          title: "复制地图",
          message: "请填入复制出的新地图的名称",
          prompt: {
            model: map.value.name + " 副本",
            type: "text",
          },
        }).onOk((data) => {
          api
            .get(useAPIStore().mapUrl + "map/copy", {
              params: { id: map.value.id, mapName: data },
            })
            .then((rs) => {
              if (rs.data) {
                $q.notify({
                  message: "复制地图成功",
                  type: "positive",
                  position: "bottom",
                });
                context.emit("update");
              }
            });
        });
      },
      navigationTypes: inject("navigationTypes"),
      mapUploader: ref(),
      remoteMapUploader: ref(),
      newGroup(val, done) {
        if (!groups.value.includes(val)) {
          groups.value.push(val);
          done(val, "add-unique");
        }
      },
    };
  },
};
</script>
